package com.ll.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.util.UuidUtils;
import com.ll.gulimall.product.service.CategoryBrandRelationService;
import com.ll.gulimall.product.vo.Catelog2Vo;
import com.sun.xml.internal.bind.v2.TODO;
import com.sun.xml.internal.ws.util.xml.CDATA;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.common.utils.PageUtils;
import com.ll.common.utils.Query;

import com.ll.gulimall.product.dao.CategoryDao;
import com.ll.gulimall.product.entity.CategoryEntity;
import com.ll.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    RedissonClient redisson;

    // 测试本地缓存
    //private Map<String,Object> cache=new HashMap<String,Object>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类数据
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装是父子的树形解构
        //2.1找到所有一级分类
        List<CategoryEntity> leve1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(muen -> {
                    //找到当前菜单对应的子菜单然后放进去
                    muen.setCategoryChildren(getCategoryChildren(muen, entities));
                    return muen;
                })
                .sorted((muen1, muen2) ->
                        {
                            return (muen1.getSort() == null ? 0 : muen1.getSort()) - (muen2.getSort() == null ? 0 : muen2.getSort());
                        }
                )
                .collect(Collectors.toList());
        return leve1Menus;
    }

    @Override
    public void removeMuensById(List<Long> asList) {
        //TODO 检查该分类是否可以被删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> catelogPath = new ArrayList<>();
        findCategoryParent(catelogId, catelogPath);
        Collections.reverse(catelogPath);
        return catelogPath.toArray(new Long[catelogPath.size() - 1]);
    }

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 修改分类时 同时删除缓存数据
     *
     * @param category
     */
    // @CacheEvict(value = "catalog",key = "'getLevel1Categorys'")
    @CacheEvict(value = "catalog", allEntries = true)

/*    @Caching(evict = {
            @CacheEvict(value = "catalog",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "catalog",key = "'cagelogJson'")
    })*/
    @Override
    public void updateCascader(CategoryEntity category) {
        this.updateById(category);
        //同步关联表数据
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        // TODO 还有其他表
    }

    @Cacheable(value = "catalog", key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys......");
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    /**
     * 利用缓存返回数据
     *
     * @return
     */
//TODO 产生堆外内存溢出: OutOfDirectMemoryError
//1)、springboot2.以后默认使用lettuce作为操作redis的客户端。它使用netty进行网络通信。
////2)、lettuce的bug导致netty堆外内存溢出-Xmx300m; netty如果没有指定堆外内存，默认使用-Xmx300m
////...可以通过 -Dio.netty, maxDirec tMemory进行设置
////解决方案:不能使用-Dio. netty, maxDirec tMemory只去调大堆外内存。
////1)、升级Lettuce客户端。2) 、切换使用jedis
//// redisTemplate:
//// lettuce. jedis操作redis的底层客户端。Spring再次封装redisTemplate:
    @Cacheable(value = "catalog", key = "'cagelogJson'",sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogs() {

        return getCatalogsFromRedisonLock();
    }

    /**
     * 从数据库中查询分类  本地🔒
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogsFromDBLock() {

        // 使用同步代码块上锁

        synchronized (this) {
            /**
             * 查询所有分类
             */
            return findDB();
        }
    }

    /**
     * 从缓存中查询分类 分布式🔒🔒🔒
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogsFromRedisLock() {
        // 使用分布式锁  保证原子上锁 原子删锁
        String uuid = UuidUtils.generateUuid();
        //上锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        //获取锁
        if (lock) {
            Map<String, List<Catelog2Vo>> db;
            System.out.println("加锁成功");
            //加锁成功 执行业务 删除锁
            try {
                db = findDB();
            } finally {
                // 删除锁的脚本
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then return redis.call(\"del\",KEYS[1]) else return 0 end";
                //删除锁 执行脚本
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
                System.out.println("删除锁成功");
            }
            return db;
        } else {
            //没获取到锁 重试获取 200ms
            System.out.println("没有获取到锁");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogsFromRedisLock();
        }

    }


    public Map<String, List<Catelog2Vo>> getCatalogsFromRedisonLock() {
        // 使用分布式锁  保证原子上锁 原子删锁
        RLock lock = redisson.getLock("catalogJson-lock");
        //上锁
        lock.lock();
        //获取锁
        Map<String, List<Catelog2Vo>> db;
        //加锁成功 执行业务 删除  锁
        try {
            db = findDB();
        } finally {
            lock.unlock();
        }
        return db;


    }

    public Map<String, List<Catelog2Vo>> findDB2() {

        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 2.缓存没有数据 从数据库查询
            System.out.println("缓存没有数据 从数据库查询");
            List<CategoryEntity> catelog1 = this.list();
            Map<String, List<Catelog2Vo>> data = null;
            if (catelog1 != null) {
                data = catelog1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    //  封装二级分类
                    List<CategoryEntity> catelog2 = getParent_cid(catelog1, v.getCatId());
                    List<Catelog2Vo> collect2 = catelog2.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        // 分装三级分类
                        List<CategoryEntity> catelog3 = getParent_cid(catelog1, l2.getCatId());
                        List<Catelog2Vo.Catalog3Vo> collect3 = catelog3.stream().map(l3 -> {
                            Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect3);
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                    return collect2;
                }));
            }
            // 3.将数据转换未JSON存起来
            String jsonString = JSON.toJSONString(data);
            redisTemplate.opsForValue().set("catalogJSON", jsonString);
            return data;

        }
        // 将缓存的catalogJSON转为我们需要的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;

    }


    public Map<String, List<Catelog2Vo>> findDB() {
        // 2.缓存没有数据 从数据库查询
        System.out.println("缓存没有数据 从数据库查询");
        List<CategoryEntity> catelog1 = this.list();
        Map<String, List<Catelog2Vo>> data = catelog1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //  封装二级分类
            List<CategoryEntity> catelog2 = getParent_cid(catelog1, v.getCatId());
            List<Catelog2Vo> collect2 = catelog2.stream().map(l2 -> {
                Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                // 分装三级分类
                List<CategoryEntity> catelog3 = getParent_cid(catelog1, l2.getCatId());
                List<Catelog2Vo.Catalog3Vo> collect3 = catelog3.stream().map(l3 -> {
                    Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName().toString());
                    return catalog3Vo;
                }).collect(Collectors.toList());
                catelog2Vo.setCatalog3List(collect3);
                return catelog2Vo;
            }).collect(Collectors.toList());
            return collect2;
        }));
        return data;
    }

    /**
     * 根据所有分类 查询parentId=指定
     *
     * @param list
     * @param parent_id
     * @return
     */
    public List<CategoryEntity> getParent_cid(List<CategoryEntity> list, Long parent_id) {
        List<CategoryEntity> collect = list.stream().filter(item -> item.getParentCid().equals(parent_id)).collect(Collectors.toList());
        return collect;

        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findCategoryParent(Long catelogId, List<Long> catelogPath) {
        //收集分类Id
        catelogPath.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0L) {
            //他就是有父节点
            findCategoryParent(byId.getParentCid(), catelogPath);
        }
        return catelogPath;
    }

    private List<CategoryEntity> getCategoryChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> categoryChildren = all.stream()
                //所有菜单中的parentId=当前菜单的id 就是二级菜单
                .filter(CategoryEntity -> CategoryEntity.getParentCid().equals(root.getCatId()))
                .map(leve2Menus -> {
                    leve2Menus.setCategoryChildren(getCategoryChildren(leve2Menus, all));
                    return leve2Menus;
                })
                .sorted((muen1, muen2) -> {
                            return (muen1.getSort() == null ? 0 : muen1.getSort()) - (muen2.getSort() == null ? 0 : muen2.getSort());
                        }

                )
                .collect(Collectors.toList());
        return categoryChildren;
    }

}